﻿function GetWFStatus(item, itemId, listId, wfId, wfStaticName) {

    this.workflowDetailsText = null;

    // Add a div to hold the text for the modal dialog
    if ($("#workflowDetails" + itemId).length == 0) {
        $(item).after("<div id='workflowDetails" + itemId + "'></div>");
        workflowDetailsText = $("#workflowDetails" + itemId);
    } else {
        workflowDetailsText = $("#workflowDetails" + itemId);
    }

    // CReate Initiation container
    $(workflowDetailsText).html("<img style='padding-left:120px;padding-top:15px' border='0' src='/_layouts/Dotsad.WFField/images/ajax-loader.gif' />");

    // Show the dialog using jQueryUI's .dialog() function
    $(workflowDetailsText).dialog({
        create: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },
        open: true,
        modal: true
    });

    //start getting info
    this.clientContext = new SP.ClientContext.get_current();
    this.web = clientContext.get_web();
    var oList = web.get_lists().getById(listId);
    this.oItem = oList.getItemById(itemId);
    this.Item = item;
    this.ItemId = itemId;
    this.ListId = listId;
    this.WFStaticName = wfStaticName;
    this.wfAssoc = oList.get_workflowAssociations();
    this.wfAssocIdGlobal = wfId;

    clientContext.load(oItem);
    clientContext.load(wfAssoc);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededGetWFAssosiation), Function.createDelegate(this, this.onQueryFailed));

}
function onQuerySucceededGetWFAssosiation() {

    var listInfo = '';

    //Get all workflows that are assosiated with the list
    var listEnumerator = wfAssoc.getEnumerator();

    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        var wfAssocId = oList.get_id().toString();
        //only grab workflow that was setup via column props
        if (wfAssocIdGlobal == wfAssocId) {
            this.HistoryList = oList.get_historyListTitle();
            this.TaskList = oList.get_taskListTitle();
            this.WorkFlowName = oList.get_name();
        }
    }

    //get history and tasks for a workflow
    retrieveListItems();
}

//get history and tasks for a workflow
function retrieveListItems() {

    // get titles for tasks and history lists
    var listHistory = web.get_lists().getByTitle(HistoryList);
    this.listTask = web.get_lists().getByTitle(TaskList);

    //query for history items based on splistitem id
    var queryHistory = new SP.CamlQuery();
    queryHistory.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Item\' /><Value Type=\'Integer\'>' + ItemId + '</Value></Eq>' +
							'<And><Eq><FieldRef Name=\'WorkflowAssociation\' />' +
							'<Value Type=\'Text\'>{' + wfAssocIdGlobal + '} </Value>' +
							'</Eq><Eq><FieldRef Name=\'List\' /><Value Type=\'Text\'>' + ListId + '</Value>' +
							'</Eq></And></And></Where><OrderBy><FieldRef Name=\'Occurred\' Ascending=\'True\' /></OrderBy></Query></View>');
    this.collListHistoryItem = listHistory.getItems(queryHistory);

    //query for tasks items based on splistitem id
    var queryTask = new SP.CamlQuery();

    queryTask.set_viewXml('<View><Query><Where><And><And><Eq><FieldRef Name=\'WorkflowName\' /> <Value Type=\'Text\'>' + WorkFlowName + '</Value></Eq>' +
						  '<Eq><FieldRef Name=\'WorkflowListId\' /><Value Type=\'Text\'>' + ListId + '</Value></Eq></And><Eq>' +
						  '<FieldRef Name=\'WorkflowItemId\' /><Value Type=\'Text\'>' + ItemId + '</Value></Eq></And></Where></Query></View>');


    this.collListTaskItem = listTask.getItems(queryTask);

    clientContext.load(listTask);
    clientContext.load(this.collListTaskItem);
    clientContext.load(this.collListHistoryItem);
    clientContext.executeQueryAsync(
		Function.createDelegate(this, this.onQuerySucceeded),
		Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {


    //build html content for dialog window
    var tabs = "<div id='tabs'><ul><li><a href='#tabs-1'>History</a></li><li><a href='#tabs-2'>Tasks</a></li>" +
			  "</ul><div id='tabs-1'>";
    tabs += "<div class='maincarousel'>";
    tabs += GetCarousel(collListHistoryItem, 'History');
    tabs += "</div>";
    tabs += "</div><div id='tabs-2'>";
    tabs += "<div class='maincarousel'>";
    tabs += GetCarousel(collListTaskItem, 'Task');
    tabs += "</div>";
    tabs += "</div></div>";

    $(workflowDetailsText).html("");
    // Add the assembled markup to the container we built for it
    $(workflowDetailsText).html(tabs);

    //set prev/net for tasks and history
    MakeNextPrev('Task');
    MakeNextPrev('History');

    //set dialog size
    $(workflowDetailsText).dialog("option", "minHeight", 500);
    $(workflowDetailsText).dialog("option", "minWidth", 500);

    //setter
    $(workflowDetailsText).dialog("option", "position", 'center');

    //setter
    $(workflowDetailsText).dialog("option", "buttons", [
    {
        text: "Ok",
        click: function () {
            $(this).dialog("close");
            $(this).remove();
        }
    }
]);


    var WorkFlowStatus = ['Not Started', 'Failed On Start', 'In Progress', 'Error Occurred', 'Stopped By User', 'Completed', 'Failed On Start - Retrying', 'Error Occurred - Retrying',
	                      'View Query Overflow', "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", 'Canceled', 'Approved', 'Rejected'];

    //set dialog title
    $(workflowDetailsText).dialog("option", "title", WorkFlowName + " : " + WorkFlowStatus[oItem.get_item(WFStaticName)]);

    //show dialog 30px from the top of the page
    $(".ui-dialog").css('top', '30px');
    //create tabs
    $("#tabs").tabs();
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function GetCarousel(itemCollection, name) {

    var totalItemCount = itemCollection.get_count();
    if (totalItemCount == 0) {
        return "No Items";
    } else {
        var tabs = "";
        var count = 0;
        var listItemEnumerator = itemCollection.getEnumerator();
        while (listItemEnumerator.moveNext()) {

            var oListItem = listItemEnumerator.get_current();

            if (count % 3 == 0)
                tabs += "<div class='showarea" + name + "' style='min-height:400px'>";

            if (name == 'Task') {
                tabs += GetTaskItem(oListItem, count);
            }
            else {
                tabs += GetHistoryItem(oListItem, count);
            }
            count++;

            if (count % 3 == 0) {
                tabs += "</div>";
            }

            if (totalItemCount == count && count % 3 != 0) {
                tabs += "</div>";
            }
        }

        if (totalItemCount > 3) {

            tabs += "<a href='#carouselPrev" + name + "' class='leftarrow" + name + "' title='Previous'><img border='0' src='/_layouts/images/pprevoff.gif' /></a>     " +
	"<a href='#carouselNext" + name + "' class='rightarrow" + name + "' title='Next'><img border='0' src='/_layouts/images/pnextoff.gif' /></a>";

        }
        return tabs;
    }
}

function GetHistoryItem(oListItem, count) {

    var eventId = oListItem.get_item('Event');
    var WorkflowEvents = ["None", "Workflow Started", "Workflow Completed", "Workflow Cancelled", "Workflow Deleted", "Task Created", "Task Completed", "Task Modified", "Task RolledBack", "Task Deleted", "Workflow Error", "Workflow Comment"];

    var outHistory = "<table>";
    // Add the information to the dialog
    outHistory = "<table width='100%'><tr><td># " + (count + 1) +
	"</td><td>" + GetDate(oListItem.get_item('Occurred')) + "</td></tr><tr><td>User ID:</td><td>" +
	GetUser(oListItem, 'User') + "</td></tr><tr><td>Event Type:</td><td>" +
	WorkflowEvents[eventId] + "</td></tr><tr><td style='vertical-align:top; width: 80px;'>Description:</td><td>" +
	GetText(oListItem, 'Description') + "</td></tr><tr><tdstyle='vertical-align:top; width: 80px;'>Outcome:</td><td>" +
	GetText(oListItem, 'Outcome') + "</td></tr><tr> <td colspan=\'2\'><hr /></td></tr></table>";

    return outHistory;
}

function GetDate(date) {
    return date.toDateString() + " " + date.toLocaleTimeString();
}

function GetText(item, value) {

    var text = item.get_item(value);

    if (text == null)
        return "";
    else
        return text;
}

function GetUser(item, value) {

    var assignedTo = item.get_item(value)
    if (assignedTo != null) {
        var assignedToName = assignedTo.get_lookupValue();
        var assignedToId = assignedTo.get_lookupId();
        assignedTo = "<a href='/_layouts/userdisp.aspx?ID=" + assignedToId + "&Source=" + location.href + "'>" + assignedToName + "</a>";
    }
    else {
        assignedTo = "N/A";
    }

    return assignedTo;
}


function GetTaskItem(oListItem, count) {

    var tabs = "";

    var PercentComplete = oListItem.get_item('PercentComplete');
    if (PercentComplete == null) {
        PercentComplete = "0";
    } else {
        // Format Percent Complete          
        PercentComplete = 100 * parseFloat(PercentComplete);
    }


    var taskUrl = "<a href='/_layouts/WrkTaskIP.aspx?List=" + listTask.get_id().toString() + "&ID=" + oListItem.get_item('ID') + "&Source=" + location.href + "'>" + oListItem.get_item('Title') + "</a>";


    tabs += "<table width='100%'> <tr> <td style='vertical-align:top; width: 80px;'># " + (count + 1) + "</td> <td> " +
                    taskUrl + "</td> </tr> <tr> <td> Assigned to: </td> <td>" +
                    GetUser(oListItem, 'AssignedTo') + "</td> </tr> <tr> <td> Priority: </td> <td> " + oListItem.get_item('Priority') +
                    " </td> </tr> <tr> <td> Complete: </td> <td> " + PercentComplete + " % </td> </tr> <tr> <td> Due: </td> <td> " +
                    GetDate(oListItem.get_item('DueDate')) + " </td> </tr> <tr> <td colspan=\'2\'> <hr /> </td> </tr> </table>";
    return tabs;

}

function MakeNextPrev(name) {

    //$('div.showarea').fadeOut(0);
    $('div.showarea' + name).hide();
    //$('div.showarea:first').fadeIn(500);
    $('div.showarea' + name + ':first').show();

    $('a.leftarrow' + name + ', a.rightarrow' + name).click(function (ev) {
        //prevent browser jumping to top
        ev.preventDefault();

        //get current visible item
        var $visibleItem = $('div.showarea' + name + ':visible');

        //get total item count
        var total = $('div.showarea' + name).length;

        //get index of current visible item
        var index = $visibleItem.prevAll().length;

        //if we click next increment current index, else decrease index
        $(this).attr('href') === '#carouselNext' + name ? index++ : index--;

        //if we are now past the beginning or end show the last or first item
        if (index === -1) {
            index = total - 1;
        }
        if (index === total) {
            index = 0
        }

        //hide current show item
        $visibleItem.hide();

        //fade in the relevant item
        $('div.showarea' + name + ':eq(' + index + ')').fadeIn(500);
    });
}